<?php
/**
 * Created by PhpStorm.
 * User: v_jingzhili
 * Date: 2019/3/27
 * Time: 11:11
 */


namespace Lib\Base;


class View
{
    /**
     * @var \smarty
     */
    static $smartyObject;

    /**
     * 模板引擎
     * @var smarty
     * @access protected
     */
    private $smarty;

    /**
     * 初始化
     *
     * @return \Redis|$this
     */
    public static function init()
    {
        if (!self::$smartyObject) {
            try {
                self::$smartyObject = new self();
            } catch (Exception $e) {
                exit(__FILE__ . "," . __LINE__ . ",系统繁忙，请稍后再试");
            }
        }
        return self::$smartyObject;
    }

    private function __construct()
    {
        //配置数据量
        if (!defined('TMPL_TEMPLATE_SUFFIX') || !defined('TMPL_TEMPLATE_DIR') || !defined('TMPL_COMPILE_DIR') || !defined('TMPL_LEFT_DELIMITER') || !defined('TMPL_RIGHT_DELIMITER')) {
            recordAMSLog(__FILE__ . "," . __LINE__ . ",请完成 Smarty 模板引擎配置");
            exit(__FILE__ . "," . __LINE__ . ",请完成 Smarty 模板引擎配置");
        }
        $this->smarty = new \Smarty();
        //修改左定界符
        $this->smarty->left_delimiter = TMPL_LEFT_DELIMITER;
        //修改右定界符
        $this->smarty->right_delimiter = TMPL_RIGHT_DELIMITER;
        //修改模板文件路径
        $this->smarty->template_dir = TMPL_TEMPLATE_DIR;
        //修改的编译路径
        $this->smarty->compile_dir = TMPL_COMPILE_DIR;
        recordAMSLog(__FILE__ . "," . __LINE__ . ",初始化模板引擎");
    }

    /**
     * 加载模板和页面输出 可以返回输出内容
     * @access public
     * @param string $templateFile 模板文件名
     * @return mixed
     */
    public function display($templateFile)
    {
        //模板文件后缀名
        $suffix = TMPL_TEMPLATE_SUFFIX;
        //模板文件路径
        $viewPath = TMPL_TEMPLATE_DIR;

        $filename = $viewPath.$templateFile.$suffix;
        if(!file_exists($filename)){
            recordAMSLog(__FILE__ . "," . __LINE__ . ",Smarty_display 模板文件不存在：" . $filename);
            exit(__FILE__ . "," . __LINE__ . ",Smarty_display 模板文件不存在：" . $filename);
        }
        $this->smarty->display($filename);
    }

    /**
     * 模板变量赋值
     * @access public
     * @param mixed $name
     * @param mixed $value
     */
    public function assign($name, $value='')
    {
        if(empty($name)){
            recordAMSLog(__FILE__ . "," . __LINE__ . ",assign 变量名不能为空");
            exit(__FILE__ . "," . __LINE__ . "assign 变量名不能为空");
        }
        recordAMSLog(__FILE__ . "," . __LINE__ . ",Smarty_assign_name:" . $name . "Smarty_assign_value:" . var_export($value, true));
        $this->smarty->assign($name, $value);
    }

}